package org.crazyit.activiti_d5._3_QueryUsersByGroup;

import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.crazyit.activiti_d3._3_UpdateUser.UpdateUser;

import java.util.List;
import java.util.UUID;

public class QueryUsersByGroup {

    public static void main(String[] args) {

        //1. 创建流程引擎
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();

        //2. 得到身份认证服务实例
        IdentityService identityService = engine.getIdentityService();

        //3. 保存两个用户
        String userId1 = UUID.randomUUID().toString();
        String userId2 = UUID.randomUUID().toString();
        UpdateUser.createUser(identityService, userId1,"张经理","young","yangenxiong@163.com","abc");
        UpdateUser.createUser(identityService, userId2,"李经理","young2","yangenxiong@163.com","abc");

        //4. 保存一个用户组
        Group group = createGroup(identityService, UUID.randomUUID().toString(), "经理组", "manager");

        //5. 将两个用户分配到用户组下
        identityService.createMembership(userId1,group.getId());
        identityService.createMembership(userId2,group.getId());

        //6. 查询已经配置到经理组下的用户信息, 并打印
        List<User> users = identityService.createUserQuery().memberOfGroup(group.getId()).list();
        System.out.println("经理组有以下人员:");
        for (User user : users) {
            System.out.println(user.getFirstName());
        }

    }

    public static Group createGroup(IdentityService identityService, String id, String name, String type) {

        //1. 调用newGroup 方法创建Group 实例
        Group group = identityService.newGroup(id);

        //2. 设置Group 实例的各个属性值
        group.setName(name);
        group.setType(type);

        //3. 保存Group 实例数据到数据库
        identityService.saveGroup(group);

        //4. 返回已经保存的Group 实例
        return identityService.createGroupQuery().groupId(id).singleResult();

    }

}
